/* $Id: game.cc jjs $ */
/*
   Copyright (C) 2007 by Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>
   Part of the Moros Project http://moros.sourceforge.net/

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 2 or any
   later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define DEBUG_ROUTINE "game"

#include "game.h"
#include "user.h"
#include "../general/log.h"
#include "../general/util.h"

const char* join_types[] = {
	"Open",
	"Moderated",
	"Spectators",
	"Private"
};
const int join_elms=4;

const char* goal_types[] = {
	"Mayor player",
	"Time",
	"Victory points",
	"Target city",
	"Target city and time"
};
const int goal_elms=5;

std::string game::join_str() {
	std::string res="";
	if (join>=0 && join<join_elms) res=join_types[join];
	return res;
}

std::string game::goal_str() {
	std::string res="";
	if (goal>=0 && goal<goal_elms) res=goal_types[goal];
	return res;
}

void game::save(channel *ch) {
	ch->write("game", id);
	ch->write("name", name);
	ch->write("descr", description);
	ch->write("owner", owner);
	ch->write("join", join);
	ch->write("goal", goal);
	ch->write("map", map);
	ch->write("url", url);
	vector<party>::iterator i;
	for(i=parties.begin(); i!=parties.end(); i++) {
		i->save(ch);
	}
}

void game::server_save(channel *ch) {
    ch->write("game", id);
    ch->write("join", join);
    ch->write("goal", goal);
	vector<party>::iterator i;
	for(i=parties.begin(); i!=parties.end(); i++) {
		i->save(ch);
	}
}

long load_game(channel *ch) {
	if (ch->key=="game") {
		long id=atol(ch->value.c_str());
		game g;
		if (games.count(id)>0) g=games[id];
		else g.id=id;
		if (ch->peek("timestamp")) {
			ch->next();
			g.timestamp=atol(ch->value.c_str());
		}
		if (ch->peek("name")) {
			ch->next();
			g.name=ch->value;
		}
		if (ch->peek("descr")) {
			ch->next();
			g.description=ch->value;
		}
		if (ch->peek("owner")) {
			ch->next();
			g.owner=ch->value;
		}
		if (ch->peek("join")) {
			ch->next();
			g.join=toint(ch->value);
		}
		if (ch->peek("goal")) {
			ch->next();
			g.goal=toint(ch->value);
		}
		if (ch->peek("map")) {
			ch->next();
			g.map=ch->value;
		}
		if (ch->peek("url")) {
			ch->next();
			g.url=ch->value;
		}
		while (ch->peek("party")) {
			ch->next();
			g.parties.push_back(load_party(ch));
		}
		games[id]=g;
        return id;
	}
	return 0;
}

game get_game(long id) {
	return games[id];
}

map<long, game> games;
